package com.hmsm.server.common;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.apache.log4j.Logger;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import com.lzyyj.gmis.base.service.IModuleService;

public class AllContext {
	private static final Logger log = Logger.getLogger(AllContext.class);
	private static ApplicationContext appContext = null;

	private static Map<String, Object> daoBean = null;// Dao javaBean
	private static Map<String, Object> serviceBean = null;// Logc javaBean

	public static ApplicationContext getAppContext() {
		if (appContext == null) {
			//log.info("重新加载spring管理类");
			String[] locations = { "applicationContext.xml",
					"applicationContextDao.xml", "applicationContextService.xml",
					"applicationContextAction.xml" };
			appContext = new ClassPathXmlApplicationContext(locations);
			//log.info("加载spring管理类结束");
			// 创建javaBean
			createBeanFactor();

		}
		return appContext;
	}

	public static void init(ApplicationContext ctxVal) {
		appContext = ctxVal;
		// 创建javaBean
		createBeanFactor();
		CommonUtil.init();//初始化全局参数
	}

	/**
	 * 获取spirng对象
	 * 
	 * @param beanName
	 * @return
	 */
	public static Object getBean(String beanName) {
		return getAppContext().getBean(beanName);
	}
	
	/**
	 * 获取dao对象
	 * 
	 * @param beanClass
	 * @return
	 * @author 舒俊
	 */
    @SuppressWarnings("unchecked")
	public static Object getBeanDao(Class beanClass){
    	Object obj = daoBean.get(beanClass.getSimpleName());
    	if(obj==null){
    		obj = appContext.getBean(beanClass);
    		if(obj == null){
        		log.error("错误的获取javaBean:"+beanClass.getName());
    		}
    	}
    	return obj;
    }
    
    /**
     * 获取service对象
     * @param beanClass
     * @return
     * @author 舒俊
     */
    @SuppressWarnings("unchecked")
	public static Object getBeanService(Class beanClass){
    	Object obj = null;
    	
    	if (beanClass.isInterface()){
        	obj = appContext.getBeanNamesForType(beanClass);
        	for (String beanName:((String[])obj)){
        		obj = appContext.getBean(beanName);
        		if (obj !=null){
        			break;
        		}
        	}
    	}else{
        	obj = serviceBean.get(beanClass.getSimpleName());
    	}
    	if(obj==null){
    		log.error("错误的获取javaBean:"+beanClass.getName());
    	}
    	
    	return obj;
    }

	/**
	 * 创建spring DAO和Service的javaBean
	 */
	public static void createBeanFactor() {
		String[] names = getAppContext().getBeanDefinitionNames();
		if (daoBean == null) {
			daoBean = new HashMap<String, Object>();
		}
		if (serviceBean == null) {
			serviceBean = new HashMap<String, Object>();
		}
		for (int i = 0; i < names.length; i++) {
			String javaBeanName = names[i];
			// HibernateEntityDao 是抽象bean，应避免实例化
			if (javaBeanName.endsWith("Dao")&&!javaBeanName.equalsIgnoreCase("HibernateEntityDao")) {
				Object obj = getBean(javaBeanName);
				// dao
				javaBeanName = javaBeanName.substring(0, 1).toUpperCase() + javaBeanName.substring(1, javaBeanName.length());
				//log.info("创建Dao javaBean --> " + javaBeanName);
				daoBean.put(javaBeanName, obj);
			} else if (javaBeanName.endsWith("Service")&&!javaBeanName.equalsIgnoreCase("baseService")) {
				// service
				Object obj = getBean(javaBeanName);
				// dao
				javaBeanName = javaBeanName.substring(0, 1).toUpperCase()
						+ javaBeanName.substring(1, javaBeanName.length());
				//log.info("创建Service javaBean --> " + javaBeanName);
				serviceBean.put(javaBeanName, obj);
			}
		}
		for(Entry<String, IModuleService> entry:getAppContext().getBeansOfType(IModuleService.class).entrySet()){
			try {
				entry.getValue().start();
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

	}

	public static List<?> findServicesBy(Class<?> class1) {
		List<Object> list = new ArrayList<Object>();
		Map<String, ?> obj = getAppContext().getBeansOfType(class1);
		for(Object entry: obj.values()){
			list.add(entry);
		}
		return list;
	}

}
